package com.jf.controller.test;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.jf.model.Logincode;
import com.jf.pay.sm.SmsUtil;
import com.jf.utils.CommonUtil;
import com.jf.utils.StringUtils;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class SsmController  extends Controller {

    /**
     * 用户获取验证码
     */
    public void gainCode() {
        String phone = getPara("phone");//用户手机号
        String type = getPara("type");//类型0:代表注册1：代表忘记密码密码（修改密码）2:修改手机
        Record record = new Record().set("code", "0");
        Calendar c = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cretime = formatter.format(c.getTime());
        Map<String, Object> map = new HashMap<String, Object>();
        //验证参数
        boolean b = !StringUtils.isEmpty(phone,type);
        if(!b){
            record.set("code", "0");
            record.set("msg", "参数不对");
            renderJson(record);
            return;
        }
        HttpSession session = this.getSession();
        String code = CommonUtil.getRandomCode();//验证码
        String templateCode="";
        try {
            if ("0".equals(type)) {//代表注册
                templateCode="SMS_142565034";
            }else if ("1".equals(type)) {//1：代表忘记密码密码（修改密码）
                templateCode="SMS_142565033";
            }else{//2:修改手机
                templateCode="SMS_142565032";
            }
            SendSmsResponse response = SmsUtil.sendSms(phone, code,templateCode);
            if("OK".equals(response.getCode())){
                session.setAttribute(phone, code);
                session.setMaxInactiveInterval(10*60);
                map.put("code",code);
                Logincode logincode=new Logincode();
                logincode.setPhone(phone);
                logincode.setCode(code);
                logincode.set("create_time", cretime);
                try {
                    logincode.save();
                    record.set("code", "1").set("msg", "获取成功").set("data", map);
                } catch (Exception e) {
                    e.printStackTrace();
                    record.set("msg", "获取失败").set("data", map);
                }
            }else{
                record.set("msg", "获取失败").set("data", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            record.set("msg", "获取失败").set("data", map);
        }
        renderJson(record);
    }
}
